//
//  FPGlobalViewController.m
//  FilmParadise
//
//  Created by lanou3g on 15/7/20.
//  Copyright (c) 2015年 DLYgroup. All rights reserved.
//

#import "FPGlobalViewController.h"
#import "FPCollectionItem.h"
#import "FPColTabViewCell.h"
#import "FPRankModel.h"
#define kRandomColor(a) kColor(arc4random_uniform(256), arc4random_uniform(256), arc4random_uniform(256),(a))
#define kColor(r, g, b ,a) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:(a)]
#define kSourthUSAUrl @"http://api.m.mtime.cn/TopList/TopListDetailsByRecommend.api?pageIndex=1&pageSubAreaID=2015"
#define kBankLandUrl @"http://api.m.mtime.cn/TopList/TopListDetailsByRecommend.api?pageIndex=1&pageSubAreaID=2020"
#define kHongKongUrl @"http://api.m.mtime.cn/TopList/TopListDetailsByRecommend.api?pageIndex=1&pageSubAreaID=2016"
#define kTaiWaiUrl @"http://api.m.mtime.cn/TopList/TopListDetailsByRecommend.api?pageIndex=1&pageSubAreaID=2019"
#define kJanpanUrl @"http://api.m.mtime.cn/TopList/TopListDetailsByRecommend.api?pageIndex=1&pageSubAreaID=2017"
#define kHanGuoUrl @"http://api.m.mtime.cn/TopList/TopListDetailsByRecommend.api?pageIndex=1&pageSubAreaID=2018"
@interface FPGlobalViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)NSArray *topLists;
/**循环创建*/
@property(nonatomic,strong)UICollectionView *collectionView;
/**循环创建button*/
@property(nonatomic,strong)UIButton *button;
@property(nonatomic,strong)NSArray *urlArray;
@property(nonatomic,strong)NSArray *globalArrayl;
@property(nonatomic,strong)NSMutableArray *sourthArray;
@property(nonatomic,strong)NSMutableArray *bankArray;
@property(nonatomic,strong)UIView *lineView;
@property(nonatomic,strong)NSMutableArray *HongKongArray;
@property(nonatomic,strong)NSMutableArray *TAiWaiArray;
@property(nonatomic,strong)NSMutableArray *JanpanArray;
@property(nonatomic,strong)NSMutableArray *HanGuoArray;
@property(nonatomic,strong)UIView *labelView;
@end


@implementation FPGlobalViewController
- (NSMutableArray *)sourthArray
{
    if (!_sourthArray) {
        _sourthArray = [NSMutableArray array];
    }
    return _sourthArray;
}
- (NSMutableArray *)bankArray
{
    if (!_bankArray) {
        _bankArray = [NSMutableArray array];
    }
    return _bankArray;
}

- (NSMutableArray *)HongKongArray
{
    if (!_HongKongArray) {
        _HongKongArray = [NSMutableArray array];
    }
    return _HongKongArray;
}- (NSMutableArray *)TAiWaiArray
{
    if (!_TAiWaiArray) {
        _TAiWaiArray = [NSMutableArray array];
    }
    return _TAiWaiArray;
}
- (NSMutableArray *)JanpanArray
{
    if (!_JanpanArray) {
        _JanpanArray = [NSMutableArray array];
    }
    return _JanpanArray;
}
- (NSMutableArray *)HanGuoArray
{
    if (!_HanGuoArray) {
        _HanGuoArray = [NSMutableArray array];
    }
    return _HanGuoArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.topLists = @[@"北美",@"内地",@"香港",@"台湾",@"日本",@"韩国"];
    self.urlArray = @[kSourthUSAUrl,kBankLandUrl,kHongKongUrl,kTaiWaiUrl,kJanpanUrl,kHanGuoUrl];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"cgClear"] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.backgroundColor = [UIColor purpleColor];
    UIView *statusBarView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth , 20)];
    statusBarView.backgroundColor = [UIColor purpleColor];
    [self.view addSubview:statusBarView];
    self.globalArrayl = @[self.sourthArray,self.bankArray,self.HongKongArray,self.TAiWaiArray,self.JanpanArray,self.HanGuoArray];
    [self creatCollectionView];
    [self creatLabel];
    [self analysisdata];
}
#pragma mark --- 添加滚动视图
- (void)creatCollectionView
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 94,kScreenWidth , kScreenHeight-94) collectionViewLayout:layout];
 
        self.collectionView.delegate = self;
        self.collectionView.dataSource = self;
        self.collectionView.pagingEnabled = YES;
        self.collectionView.bounces = YES;
        [self.view addSubview:_collectionView];

}
- (void)creatLabel
{
    //label间的的距离
    CGFloat pace = 10;
    CGFloat LabelW = (kScreenWidth - 7*pace)/6;
    self.lineView= [[UIView alloc]initWithFrame:CGRectMake(kImageW(pace),30, LabelW, 2)];
    self.labelView = [[UILabel alloc]initWithFrame:CGRectMake(kScreenWidth, 64, kScreenWidth, kImageH(30))];
    self.labelView.backgroundColor = [UIColor colorWithRed:0.11 green:0.88 blue:0.90 alpha:0.5];
    self.labelView.userInteractionEnabled = YES;
    self.lineView.backgroundColor = kRandomColor(1.0);
    [self.labelView addSubview:self.lineView];
  
    [self.view addSubview:self.labelView];
    for (int i = 0; i <self.topLists.count; i++) {
        self.button = [[UIButton alloc]initWithFrame:CGRectMake( LabelW*i + pace, 0, LabelW, kImageH(30))];
        [self.button addTarget:self action:@selector(clickButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        self.button.tag = 500 + i;
        NSString *str = self.topLists[i];
        [self.button setTitle:str forState:UIControlStateNormal];
        [self.button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [self.labelView addSubview:self.button];
        pace += 10;
    }
}

- (void)clickButtonAction:(UIButton *)sender
{
    CGFloat pace = 10;
    CGFloat LabelW = (kScreenWidth - 7*pace)/6;
    switch (sender.tag)
    {
        case 500:
            self.lineView.transform = CGAffineTransformMakeTranslation(0, 0);
            self.collectionView.contentOffset = CGPointMake(0, 0);
            break;
        case 501:
            self.lineView.transform = CGAffineTransformMakeTranslation(1*kImageW(10) + LabelW, 0);
            self.collectionView.contentOffset = CGPointMake(kScreenWidth, 0);

            break;
        case 502:
            self.lineView.transform = CGAffineTransformMakeTranslation(2*kImageW(10)+2*LabelW, 0);
            self.collectionView.contentOffset = CGPointMake(kScreenWidth * 2, 0);

            break;
        case 503:
            self.lineView.transform = CGAffineTransformMakeTranslation(3*kImageW(10)+3*LabelW,0);
            self.collectionView.contentOffset = CGPointMake(kScreenWidth * 3, 0);

            break;
        case 504:
            self.lineView.transform = CGAffineTransformMakeTranslation(4*kImageW(10)+4*LabelW, 0);
            self.collectionView.contentOffset = CGPointMake(kScreenWidth * 4, 0);

            break;
        case 505:
            self.lineView.transform = CGAffineTransformMakeTranslation(5*kImageW(10)+5*LabelW, 0);
            self.collectionView.contentOffset = CGPointMake(kScreenWidth * 5, 0);

            break;
 
        default:
            break;
    }
}

#pragma mark======解析数据
#warning 使用RankModel模型
- (void)analysisdata
{
    for (int i = 0; i< self.urlArray.count; i++)
    {
        NSURL *url = [NSURL URLWithString:self.urlArray[i]];
        //创建请求对象
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:1.0];
        //开启异步联接 用队列的形式进行一步请求数据
        [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            if (data == nil) return ;
            
            //请求的所有数据已经全部接受完成的时候 ,才会执行Block快里的方法 此时data就是我们请求下来的数据它会自动传回到这个参数上面
            NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            
            NSArray *movies = dic[@"movies"];
          
            for (NSDictionary *smallDic in movies)
            {
                FPRankModel *model = [FPRankModel fpRankModelSetValueWithDictionary:smallDic];
                [self.globalArrayl[i] addObject:model];
            }
          //  NSLog(@"=========%@",self.globalArrayl[1]);
            [self.collectionView reloadData];
        }];
        
    }
}
#pragma mark ==========collection代理方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.topLists.count;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(kScreenWidth, kScreenHeight - 94);
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 0;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 0;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIndentifier = @"_cell";
    [collectionView registerClass:[FPCollectionItem class] forCellWithReuseIdentifier:cellIndentifier];
    FPCollectionItem *item = [collectionView dequeueReusableCellWithReuseIdentifier:cellIndentifier forIndexPath:indexPath];
    item.tableView.delegate = self;
    item.tableView.dataSource = self;
    item.tableView.tag = indexPath.row + 100;
    [item.tableView reloadData];
    return item;
   
}

- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath{
    FPCollectionItem *item = (FPCollectionItem *)cell;
    [item.tableView reloadData];
}

#pragma mark ==============taab代理方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.globalArrayl[tableView.tag-100] count];


}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIndentifier = @"tabcell";
    [tableView registerClass:[FPColTabViewCell class] forCellReuseIdentifier:cellIndentifier];
    FPColTabViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier forIndexPath:indexPath];
    NSInteger row = tableView.tag-100;
    switch (row) {
            case 0:
            {
                FPRankModel * model = self.globalArrayl[row][indexPath.row];
                [cell cellForModel:model];

            }
                break;
            case 1:
            {
                 FPRankModel * model = self.bankArray[indexPath.row];
                [cell cellForModel:model];
            
            }
                break;
            case 2:
            {
                 FPRankModel * model = self.HongKongArray[indexPath.row];
                [cell cellForModel:model];

            }
                break;
            case 3:
            {
                FPRankModel * model = self.TAiWaiArray[indexPath.row];
                [cell cellForModel:model];

            }
                break;
            case 4:
            {
                 FPRankModel * model = self.JanpanArray[indexPath.row];
                [cell cellForModel:model];

                
            }
                break;
            case 5:
            {
                 FPRankModel * model = self.HanGuoArray[indexPath.row];
                [cell cellForModel:model];

                
            }
                break;
                
            default:
                break;
        }
       return cell;

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 160;
}
#pragma mark ===========添加子控制器
- (void)viewWillAppear:(BOOL)animated
{
    [UIView animateWithDuration:1 animations:^{
        self.labelView.x = 0;
    } completion:^(BOOL finished)//当上一个block执行结束再执行下一个block
     {
         
         [UIView animateWithDuration:0.5 animations:^{
             self.labelView.x = 100;
         } completion:^(BOOL finished)//当上一个block执行结束再执行下一个block
          {
              [UIView animateWithDuration:0.3 animations:^{
                  
                  self.labelView.x = 0;
                  
              }completion:^(BOOL finished) {
                  [UIView animateWithDuration:0.2 animations:^{
                      self.labelView.x = 40;
                  }completion:^(BOOL finished) {
                      
                      [UIView animateWithDuration:0.1 animations:^{
                          self.labelView.x = 0;
                      }];
                      
                      
                  }];
              }];
          }];
     }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
